#include "heroz_screens.hh"
#include <cstdio>
#include <fstream>
#include <iostream>
#include <stdexcept>

using namespace std;

void Levels::load(const char *fname) {
  unsigned int i;
  int j, k, l, m;
  string line;
  ifstream in(fname);
  int clevel = 0; //current level

  if(in) {
    while(getline(in, line)) {
      if(line.size() > 0) {
	const char *cstr = line.c_str();

	if(line[0] == '#') continue;
	if(sscanf(cstr, "level = %u", &i) == 1) {
	  if(i >= levels.size()) levels.resize(i + 1);
	  clevel = i;
	} else if(sscanf(cstr, "conn %u = %d %d %d %d", &i, &j, &k, &l, &m) == 5) {
	  ConnectionType &conn = levels.at(clevel).conns;
	  if(i >= conn.size()) conn.resize(i + 1);
	  conn.at(i).e = j;
	  conn.at(i).n = k;
	  conn.at(i).w = l;
	  conn.at(i).s = m;
	} else if(sscanf(cstr, "start = %u", &i) == 1) {
	  levels.at(clevel).start = i;
	} else if(sscanf(cstr, "playerxy = %d , %d", &j, &k) == 2) {
	  levels.at(clevel).player_x = j;
	  levels.at(clevel).player_y = k;
	} else {
	  throw std::runtime_error("error reading line: " + line);
	}
      }
    }
  } else {
    throw runtime_error("can not load level");
  }
}

Levels::Connection::Connection() {
  e = n = s = w = -1;
}
